<template>
<div>
  商品入库
  <el-form   :model="queryParams" ref="queryForm" size="small" :inline="true">
    <el-form-item label="产品名称" prop="">
      <el-input
        v-model="queryParams.productName"
        placeholder="请输入产品名称"
        clearable
        @keyup.enter.native="handleQuery"
      />
    </el-form-item>
    <el-form-item label="分类名称" prop="categoryName">
      <el-cascader
        v-model="queryParams.categoryIds"
        :options="categoryTree"
        placeholder="请选择分类名称"
        clearable
        :props="{ checkStrictly: true, label: 'name', value: 'id' }"
        @change="handleCategoryChange"
      ></el-cascader>
    </el-form-item>
    <el-form-item label="状态" prop="status">
      <el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 240px">
        <el-option v-for="dict in dict.type.zzsz_product_stockstatus" :key="dict.value" :label="dict.label" :value="dict.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="出\入 库" prop="operationType">
      <el-select v-model="queryParams.operationType" placeholder="出\入 库" clearable style="width: 240px">
        <el-option v-for="dict in dict.type.zzsz_product_operationtype" :key="dict.value" :label="dict.label" :value="dict.value" />
      </el-select>
    </el-form-item>


    <el-form-item>
      <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
    </el-form-item>
  </el-form>
  <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">入库</el-button>

  <el-table v-loading="loading" :data="paoductsList" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" align="center" />
    <el-table-column label="商品图片" width="120">
      <template slot-scope="scope">
        <el-image
          v-if="scope.row.productImage"
          :src="scope.row.productImage"
          fit="cover"
          :preview-src-list="[scope.row.productImage]"          style="width: 80px; height: 80px; border-radius: 4px;"
        >
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
          </div>
        </el-image>
        <div v-else class="no-image">
          <i class="el-icon-picture-outline"></i>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="产品名称" align="center" prop="productName" />
    <el-table-column label="SKU" align="center" prop="sku" />
    <el-table-column label="分类" align="center" prop="categoryName" />

    <el-table-column label="出入库类型" align="center" prop="operationType" >
      <template slot-scope="scope">
        <dict-tag :options="dict.type.zzsz_product_operationtype" :value="scope.row.operationType" />
      </template>
    </el-table-column>
    <el-table-column label="数量" align="center" prop="quantity" />
    <el-table-column label="操作人" align="center" prop="operator" />
    <el-table-column label="操作时间" align="center" prop="operateTime" width="180">
      <template slot-scope="scope">
        <span>{{ parseTime(scope.row.operateTime) }}</span>
      </template>
    </el-table-column>
    <el-table-column label="状态" align="center" prop="status">
      <template slot-scope="scope">
        <dict-tag :options="dict.type.zzsz_product_stockstatus" :value="scope.row.status" />
      </template>
    </el-table-column>
    <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
      <template slot-scope="scope">
        <el-button
          size="mini"
          type="text"
          icon="el-icon-view"
          @click="handleView(scope.row)"
        >详情</el-button>
      </template>
    </el-table-column>
  </el-table>
  <pagination
    v-show="total>0"
    :total="total"
    :page.sync="queryParams.pageNum"
    :limit.sync="queryParams.pageSize"
    @pagination="getlist"
  />

  <!-- 入库对话框 -->
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="500px"
    append-to-body
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="输入产品名称" prop="productName">
        <el-autocomplete
          v-model="form.productName"
          :fetch-suggestions="queryProduct"
          :trigger-on-focus="false"
          placeholder="请输入商品ID、SKU或名称"
          @select="handleProductSelect"
          clearable
        >
          <template slot-scope="{ item }">
            <div class="product-info">
              <div class="product-name">{{ item.productName }}</div>
              <div class="product-meta">
                <span>ID: {{ item.id }}</span>
                <span>SKU: {{ item.sku }}</span>
              </div>
            </div>
          </template>
        </el-autocomplete>
      </el-form-item>
      <!-- 入库表单内容，根据实际需求添加字段 -->
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="form.productName" placeholder="请选择产品" readonly @click="selectProduct" />
      </el-form-item>
      <el-form-item label="入库数量" prop="quantity">
        <el-input v-model.number="form.quantity" placeholder="请输入入库数量" type="number" min="1" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" placeholder="请输入备注信息" type="textarea" rows="3" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </div>
  </el-dialog>



</div>
</template>

<script>
import { listinStock } from "@/api/products/instock";
import { getCategoryName,addInStock } from '@/api/inventory/list'
import { getproductsList} from '@/api/products/product'
export default {
  name: "",
  dicts:['zzsz_product_operationtype', 'zzsz_product_stockstatus'],
  data() {
    return {
      paoductsList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,

      // 分类名称
      categoryTree: [],
      selectedCategoryIds: [],

      queryParams: {
        productName: "",
        categoryIds: []  ,// 级联选择器需要数组类型v-model
        status: "",
        operationType: "",
        pageNum: 1,
        pageSize: 10,
      },
      inStockList: [],


      // 入库对话框参数
      open: false,
      title: "",
      // 入库表单数据
      form: {
        productId: null,
        productName: "",
        quantity: 1,
        remark: ""
      },
      // 表单校验规则
      rules: {
        productName: [{ required: true, message: "请选择产品", trigger: "blur" },
          { validator: this.validateProduct, trigger: "blur" }
        ],
        quantity: [{ required: true, message: "请输入入库数量", trigger: "blur" }]
      }
    }
  },
  methods: {
    // 获得商品列表
    getlist() {
      this.loading = true;
      console.log("获得商品列表 搜索参数",this.queryParams)
      listinStock(this.queryParams).then(Response => {
        console.log("获得商品列表后端返回",Response)
        this.paoductsList = Response.rows
        this.total=Response.total
      }).catch(error => {
        console.error("获取商品列表失败:", error);
        this.loading = false;
      });
      this.loading = false
    },
    /** 查看详情 */
    handleView(row) {
      // 可以在这里添加查看详情的逻辑
      console.log("查看详情", row);
    },
    // 处理分类选择变化
    handleCategoryChange(value) {
      // 将选中的分类ID赋值给查询参数
      this.selectedCategoryIds = value || [];
    },
    // 获得分类名称 用于搜索
    getCategoryName() {
      getCategoryName().then(Response => {
        console.log("获得后端返回的分类名称",Response)
        this.categoryTree = Response.data
      }).catch(error => {
        console.error("获取分类名称失败:", error);
      });

    },



    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dictId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },


    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getlist()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },

    /** 打开入库对话框 */
    handleAdd() {
      this.title = "新增入库";
      this.form = {
        productId: null,
        productName: "",
        quantity: 1,
        remark: ""
      };
      this.open = true;
    },
    /** 提交入库表单 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 调用入库API
          const submitData = {
            ...this.form,
            // 确保提交productId而不是仅productName
            productId: this.form.productId
          };
          console.log("提交入库表单",submitData)

          addInStock(submitData).then(response => {
            this.$message.success("入库成功");
            this.open = false;
            this.getlist(); // 重新加载列表
          }).catch(error => {
            this.$message.error("入库失败: " + error.message);
          });
        }
      });
    },
    /** 取消入库操作 */
    cancel() {
      this.open = false;
      this.$refs.form.resetFields();
    },
    /** 选择产品（需要实现产品选择逻辑） */
    selectProduct() {
      // 这里可以打开产品选择对话框或页面
      this.$message.info("请实现产品选择功能");
    },
    /** 根据关键词查询商品 */
    queryProduct(queryString, callback) {
      console.log("根据关键词查询商品queryString",queryString)
      console.log("根据关键词查询商品callback",callback)
      if (!queryString) {
        callback([]);
        return;
      }

      // 判断输入的是ID、SKU还是名称
      let params = {};
      if (/^\d+$/.test(queryString)) {
        // 纯数字，按ID查询
        params.productId = queryString;
      } else if (/^[A-Za-z0-9-]+$/.test(queryString)) {
        // 字母数字组合，按SKU查询
        params.sku = queryString;
      } else {
        // 其他情况按名称查询
        params.productName = queryString;
      }

      getproductsList(params).then(response => {
        console.log("根据关键词查询商品后端返回",response)
        // 格式化数据为组件需要的格式
        callback(response.data.map(item => ({
          value: item.productName,
          ...item
        })));
      }).catch(() => {
        callback([]);
      });
    },
    /** 选择商品后处理 */
    handleProductSelect(item) {
      console.log("选择商品后处理item",item)
      this.form.productId = item.productId;
      this.form.productName = item.productName;
      this.form.sku = item.sku;
      console.log("选择商品后处理",this.form)
      // 可以自动填充其他需要的商品信息
    },

    /** 验证商品是否已选择 */
    validateProduct(rule, value, callback) {
      if (!this.form.productId) {
        callback(new Error("请从下拉列表中选择商品"));
      } else {
        callback();
      }
    },



  },
  created() {
    this.getlist();
    this.getCategoryName()
  },
}
</script>

<style scoped lang="scss">.no-image {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #c0c4cc;
  font-size: 24px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.image-slot i {
  font-size: 24px;
}
</style>
